package com.xiaobaibai.security.handler;

import com.alibaba.fastjson.JSONObject;
import com.xiaobaibai.response.ResponseCode;
import com.xiaobaibai.security.common.TokenCommon;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Component
public class TokenLogoutHandler implements LogoutHandler, LogoutSuccessHandler {

    @Autowired
    private TokenCommon tokenCommon;

    @Override
    public void logout(HttpServletRequest request, HttpServletResponse response,
                       Authentication authentication) {

        if(authentication==null)//只有登录的用户退出了,才可以换盐
            return;
        //换密匙(盐)
        tokenCommon.switchSalt();
    }

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response,
                                Authentication authentication) throws IOException, ServletException {

        response.setContentType("application/json; charset=utf-8");
        response.setCharacterEncoding("utf-8");
        response.setStatus(200);
        PrintWriter writer = response.getWriter();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", ResponseCode.SUCCESS.getCode());
        jsonObject.put("msg","登出");
        writer.write(jsonObject.toString());
    }
}
